﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;




namespace mwrf_test
{
    public partial class Form1 : Form
    {
        private int icdev = 0;                      //设备描述符
        byte[] key = { 0x20, 0x17, 0x04, 0x08, 0x01, 0x08 };       //密码
        private byte cardNumAddr = 1;               //存储卡号的绝对块地址
        //private byte passwdAddr = 4;                //密码地址
        //private byte lockFlagAddr = 6;              //锁卡标志地址
        private byte moneyAddr = 8;                 //钱包地址
        
        public Form1()
        {
            InitializeComponent();
            key[0] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd1"]));
            key[1] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd2"]));
            key[2] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd3"]));
            key[3] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd4"]));
            key[4] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd5"]));
            key[5] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd6"]));
            textBox1.Text = "xx";
            textBox2.Text = "xx";
            textBox3.Text = "xx";
            textBox4.Text = ConfigurationManager.AppSettings["pwd4"];
            textBox5.Text = ConfigurationManager.AppSettings["pwd5"];
            textBox6.Text = ConfigurationManager.AppSettings["pwd6"];
        }
        private byte BCD2BIN(byte bcd)
        {
            int bin;

            bin = ((((bcd) >> 4) * 10) + ((bcd) % 16));

            return (byte)bin;
        }
        private byte BIN2BCD(byte bin)
        {
            int bcd;

            bcd = ((((bin) / 10) << 4) + ((bin) % 10));

            return (byte)bcd;
        }

        private bool find_card()
        {
            //寻卡
            UInt16 tagtype = 0x0004;
            if (mifareone.rf_request(icdev, 1, out tagtype) != 0)
            {
                lbResult.Text = "寻卡错误!";
                return false;
            }
            //防冲突
            uint snr = 0;
            if (mifareone.rf_anticoll(icdev, 0, out snr) != 0)
            {
                lbResult.Text = "防冲突错误!";
                return false;
            }
            //选卡
            byte size = 0;
            if (mifareone.rf_select(icdev, snr, out size) != 0)
            {
                lbResult.Text = "选卡错误!";
                return false;
            }
            return true;
        }
        /*
            连接
            */
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (icdev == 0)
            {
                icdev = common.rf_init(0, 115200);
                if (icdev > 0)
                {
                    lbResult.Text = "连接成功！";
                    btnConnect.Text = "断开";
                    common.rf_beep(icdev, 5);
                }
                else
                {
                    lbResult.Text = "连接失败！";
                    icdev = 0;
                }
            }
            else
            {
                common.rf_exit(icdev);
                icdev = 0;
                lbResult.Text = "断开成功！";
                btnConnect.Text = "连接";
            }
        }

        /*
            读卡按键
            */
        private void btnAuth_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[16];

            if (!find_card())
                return;
            
            //********************** 扇区0 块1 账号部分 **********************
            //装载密码
            common.rf_load_key(icdev, 4, cardNumAddr / 4, key);

            //验证密码
            if (mifareone.rf_authentication(icdev, 4, cardNumAddr / 4) != 0)
            {
                lbResult.Text = "密码验证失败！";
                mifareone.rf_halt(icdev);
                return;
            }

            //读取卡数据
            if (mifareone.rf_read(icdev, cardNumAddr, data) != 0)
            {
                lbResult.Text = "卡号读取失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            textData.Text = Encoding.ASCII.GetString(data);

            //********************** 扇区2 块0 钱包部分 **********************
            common.rf_load_key(icdev, 4, moneyAddr / 4, key);
            if (mifareone.rf_authentication(icdev, 4, moneyAddr / 4) != 0)
            {
                lbResult.Text = "密码验证失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            //读取卡数据
            uint value;
            if(mifareone.rf_readval(icdev, moneyAddr, out value) != 0)
            {
                lbResult.Text = "钱包读取失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            textMoney.Text = (value / 100).ToString() + '.' + (value % 100).ToString();

            lbResult.Text = "读卡成功！";
            //终止对该卡操作
            mifareone.rf_halt(icdev);
        }

        /*
            写卡按钮，将文本框的数据写入卡中
            */
        private void btnWriteData_Click(object sender, EventArgs e)
        {
            if (!find_card())
                return;
            //扇区0 块1 -- 账号部分
            //装载密码
            if (common.rf_load_key(icdev, 4, cardNumAddr / 4, key) != 0)
            {
                lbResult.Text = "装载密码失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            //验证密码
            if (mifareone.rf_authentication(icdev, 4, cardNumAddr / 4) != 0)
            {
                lbResult.Text = "密码验证失败！";
                mifareone.rf_halt(icdev);
                return;
            }

            //检查卡号是否合法
            if (textData.TextLength != 16)
            {
                lbResult.Text = "卡号长度非法！";
                mifareone.rf_halt(icdev);
                return;
            }

            string data = textData.Text;
            for (int i = 0; i < 16; i++)
            {
                if (data[i] >= '0' && data[i] <= '9')
                    continue;
                else
                {
                    lbResult.Text = "卡号值非法！";
                    mifareone.rf_halt(icdev);
                    return;
                }
            }

            byte[] buff = new byte[16];
            buff = Encoding.ASCII.GetBytes(data);
            if (mifareone.rf_write(icdev, cardNumAddr, buff) != 0)
            {
                lbResult.Text = "卡号写入失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            lbResult.Text = "卡号写入成功！";
            mifareone.rf_halt(icdev);
        }

        /*
            制作新卡
            */
        private void btnMake_Click(object sender, EventArgs e)
        {
            byte[] initKey = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

            if (!find_card())
                return;

            byte cnt = 0;
            for(byte i = 0; i < 16; i++)
            {
                common.rf_load_key(icdev, 4, i, initKey);           //装载密码B
                if (mifareone.rf_authentication(icdev, 4, i) != 0)  //验证密码B
                    continue;

                if (mifareone.rf_changeb3(icdev, i, key, 0x06, 0x06, 0x06, 0x06, 0, key) != 0) //修改块3的数据
                    continue;
                cnt++;
            }

            if(cnt != 16)
                lbResult.Text = "该卡不是新卡！";
            else
                lbResult.Text = "制卡成功！";

            mifareone.rf_halt(icdev);
        }

        /*
            充值
            */
        private void btnRecharge_Click(object sender, EventArgs e)
        {
            Form2 form = new Form2();
            form.ShowDialog();
            string s = form.text;

            if (s == null || s.Length < 1)
            {
                return;
            }

            uint val;
            try
            {
                val = Convert.ToUInt32(s);
                if (val < 1 || val > 10000)
                {
                    lbResult.Text = "输入的值不正确！";
                    return;
                }
                val = val * 100;
            }
            catch
            {
                lbResult.Text = "输入的值不正确！";
                return;
            }

            if (!find_card())
                return;

            common.rf_load_key(icdev, 4, moneyAddr / 4, key);                  //装载密码
            if (mifareone.rf_authentication(icdev, 4, moneyAddr / 4) != 0)     //验证密码
            {
                lbResult.Text = "密码验证失败！";
                mifareone.rf_halt(icdev);
                return;
            }

            if(mifareone.rf_increment(icdev, moneyAddr, val) != 0)
            {
                lbResult.Text = "充值失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            lbResult.Text = "充值成功！";

            uint value;
            if (mifareone.rf_readval(icdev, moneyAddr, out value) != 0)
            {
                lbResult.Text = "钱包读取失败！";
                mifareone.rf_halt(icdev);
                return;
            }
            textMoney.Text = (value / 100).ToString() + '.' + (value % 100).ToString();
            mifareone.rf_halt(icdev);
        }

        /*
            初始化余额
            */
        private void btnInitMoney_Click(object sender, EventArgs e)
        {
            if (!find_card())
                return;
            common.rf_load_key(icdev, 4, moneyAddr / 4, key);                  //装载密码
            if (mifareone.rf_authentication(icdev, 4, moneyAddr / 4) != 0)     //验证密码
            {
                lbResult.Text = "密码验证失败！";
                mifareone.rf_halt(icdev);
                return;
            }

            if(mifareone.rf_initval(icdev, moneyAddr, 0) != 0)
            {
                lbResult.Text = "初始化余额失败！";
                mifareone.rf_halt(icdev);
                return;
            }

            lbResult.Text = "初始化余额成功！";
            textMoney.Text = "0.0";
            mifareone.rf_halt(icdev);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
        /*
         设置/显示扇区密码
           */
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //textBox1.Text = "0.0";//
        }
        /*
         * 重置扇区密码
         */
        private void button1_Click(object sender, EventArgs e)
        {
            string pwd1 = textBox1.Text.Trim();
            string pwd2 = textBox2.Text.Trim();
            string pwd3 = textBox3.Text.Trim();
            string pwd4 = textBox4.Text.Trim();
            string pwd5 = textBox5.Text.Trim();
            string pwd6 = textBox6.Text.Trim();

            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            
            cfa.AppSettings.Settings["pwd4"].Value = pwd4;
            cfa.AppSettings.Settings["pwd5"].Value = pwd5;
            cfa.AppSettings.Settings["pwd6"].Value = pwd6;
            cfa.Save();
            ConfigurationManager.RefreshSection("appSettings");

            key[0] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd1"]));
            key[1] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd2"]));
            key[2] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd3"]));
            key[3] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd4"]));
            key[4] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd5"]));
            key[5] = BIN2BCD(byte.Parse(ConfigurationManager.AppSettings["pwd6"]));
        }

        private void textData_TextChanged(object sender, EventArgs e)
        {

        }

        private void textMoney_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
